package ru.housewife.service.dishes;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.CookingDishRecipeGroupForm;
import ru.housewife.model.CookingDishRecipeGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class GetRecipesGroupTree implements HibernateAction<List<CookingDishRecipeGroupForm>> {

    @Override
    public List<CookingDishRecipeGroupForm> execute(Session session) {
        return execute(session, null);
    }

    public List<CookingDishRecipeGroupForm> execute(Session session, CookingDishRecipeGroupForm parentFrm) {
        Query q;
        if (parentFrm != null) {
            q = session.createQuery("select rg from CookingDishRecipeGroup rg where rg.parent.id=:recipeGroupId");
            q.setLong("recipeGroupId", parentFrm.getId());
        } else {
            q = session.createQuery("select rg from CookingDishRecipeGroup rg where rg.parent.id is NULL");
        }
        List<CookingDishRecipeGroup> lst = q.list();
        List<CookingDishRecipeGroupForm> result = new ArrayList<CookingDishRecipeGroupForm>(lst.size());
        for (CookingDishRecipeGroup recipeGroup : lst) {
            CookingDishRecipeGroupForm frm = createCookingDishRecipeGroupForm(recipeGroup, parentFrm);
            frm.setChilds(execute(session, frm));
            result.add(frm);
        }
        return result;
    }

    private CookingDishRecipeGroupForm createCookingDishRecipeGroupForm(CookingDishRecipeGroup recipeGroup, CookingDishRecipeGroupForm parentFrm) {
        CookingDishRecipeGroupForm frm = new CookingDishRecipeGroupForm();
        frm.setId(recipeGroup.getId());
        frm.setName(recipeGroup.getName());
        frm.setDefaultGroup(recipeGroup.isDefaultGroup());
        frm.setOrder(recipeGroup.getOrder());
        frm.setParent(parentFrm);
        return frm;
    }

}
